<template>
  <div class="main-container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content-container">
      <div class="title-container">
        <div class="title-text">鼾声</div>
      </div>
      <div class="subtitle-container">
        <el-text class="subtitle-text">鼾声分析:</el-text>
      </div>
      <div class="info-container">
        <!--
        <div class="reference-container">
          <ReferenceType class="reference-item" :icon="['fas','fa-chart-bar']" title="打鼾事件计数" :count="snoreInfo.num"/>
          <ReferenceType class="reference-item" :icon="['fas','fa-clock']" title="平均每秒打鼾时长" :count="snoreInfo.perDuration"/>
          <ReferenceType class="reference-item" :icon="['fas','fa-hourglass-half']" title="总共打鼾时长" :count="snoreInfo.totalDuration"/>
          <ReferenceType class="reference-item" :icon="['fas','fa-chart-pie']" title="打鼾占睡眠比例" :count="(snoreInfo.proportion * 100) +'%'"/>
        </div>
        -->
        <div class="reference-container">
          <ReferenceType class="reference-item" :color="'#5270C3'" :icon="['fas','fa-chart-bar']" title="打鼾事件计数" :count="snoreInfo.num + ' 次'" />
          <ReferenceType class="reference-item" :color="'#90CB75'" :icon="['fas','fa-clock']" title="平均每次打鼾时长" :count="snoreInfo.perDuration.toFixed(2) + ' 秒'"/>
          <ReferenceType class="reference-item" :color="'#FAC75B'" :icon="['fas','fa-hourglass-half']" title="总共打鼾时长" :count="snoreInfo.totalDuration.toFixed(2) + ' 秒'"/>
          <ReferenceType class="reference-item" :color="'lightcoral'" :icon="['fas','fa-chart-pie']" title="打鼾占睡眠比例" :count="(snoreInfo.proportion * 100).toFixed(2) + '%'"/>
        </div>
      </div>
      <div class="subtitle-container">
        <el-text class="subtitle-text">鼾声分时图:</el-text>
      </div>
      <div class="chart-wrapper">
        <div class="chart-container">
          <div id="SnoreChart" class="chart"></div>
        </div>
      </div>
      <div class="evaluation-wrapper">
        <div class="evaluation-content">
          <div class="evaluation-header">
            <div class="icon">
              <font-awesome-icon :icon="['fas','fa-file-alt']" size="2x" class="icon-color"></font-awesome-icon>
            </div>
            <div class="evaluation-title">鼾声评估结果：</div>
            <el-button v-if="enableEdit" class="edit-button" @click="showEditInput">
              <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
              <el-text class="edit-text">编辑</el-text>
            </el-button>
          </div>
          <div class="evaluation-body">
            <el-input type="textarea" class="evaluation-input" v-model="currentUserSnoreData.evaluation" v-if="editMode"></el-input>
            <el-text v-else :span="24" class="evaluation-display">
              {{ currentUserSnoreData.evaluation }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import ReferenceType from "@/components/ReferenceType.vue";
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import '@/assets/css/reportCard.css';
import {markRaw, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import * as echarts from "echarts";
import sleepData from "@/api/sleepData.js";
import {ElMessage} from "element-plus";
onMounted(() => {
  getSnoreData(props.currentReportId);
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts);
});
onUnmounted(() => {
  if (currentUserSnoreData.value.evaluation === evaluationBackup.value){

  }else {
    const updateSnoreDataDto = {
      reportId: props.currentReportId,
      evaluation: currentUserSnoreData.value.evaluation
    }
    sleepData.updateSnoreEvaluate(updateSnoreDataDto).then((res)=>{
      if (res.data.code === 200){
      }
    }).catch((err)=>{
      console.log(err)
    })
  }
  disposeChart()
});
const props = defineProps({
  currentReportId: Number,
  enableEdit:Boolean
});
watch(() => props.currentReportId, (newId) => {
  getSnoreData(newId);
});
watch(() => props.enableEdit, (newValue) => {
  enableEdit.value = newValue
});
const enableEdit = ref(props.enableEdit)

const loading = ref(false)
const evaluationBackup = ref('')
const getSnoreData = (reportId)=>{
  loading.value = false
  sleepData.getSnoreData(reportId).then((res)=>{
    const snoreTime = res.data.data.snoreTime
    // 计算打鼾事件的具体时间点
    createSnoreChart(snoreTime);
    snoreInfo.value = res.data.data.snoreInfo
    currentUserSnoreData.value = res.data.data
    evaluationBackup.value = currentUserSnoreData.value.evaluation
  }).catch((err)=>{
    console.log(err)
  }).finally(() => {
    loading.value = false; // 使用箭头函数包装
  });
}
//图表创建
const snoreChartInstance = ref(null);
const createSnoreChart = (snoreTime) => {
  const { startTime, frequency, snoreLabels } = snoreTime;
  const times = snoreLabels.map((_, index) => {
    const date = new Date(startTime + index * frequency);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  });
  snoreChartInstance.value = markRaw(echarts.init(document.getElementById("SnoreChart")));
  snoreChartInstance.value.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function (params) {
        let tooltipText = '';
        params.forEach(param => {
          tooltipText += `时间: ${param.name}<br/>打鼾状态: ${param.value === 1 ? '打鼾' : '不打鼾'}<br/>`;
        });
        return tooltipText;
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      top: '10%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: times,
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'category',
      data: ['不打鼾', '打鼾'],
      splitLine: {
        show: false
      }
    },
    series: [{
      name: '打鼾状态',
      type: 'line',
      smooth: true,
      data: snoreLabels,
      step: 'middle',
      symbol: 'none', // 隐藏圆点
      lineStyle: {
        color: '#87B8A6' // 设置线条颜色
      }
    }]
  });
}

//图表自适应
const resizeCharts = () => {
  if (snoreChartInstance.value) {
    snoreChartInstance.value.resize();
  }
};
const disposeChart = ()=>{
  // 销毁图表实例
  if (snoreChartInstance.value) {
    snoreChartInstance.value.dispose();
  }
  // 移除事件监听器
  window.removeEventListener('resize', resizeCharts);
}

const snoreInfo = ref({
  num:4,
  totalDuration:420,
  proportion: 46.7,
  perDuration:105
});

const currentUserSnoreData = ref({
  evaluation:''
})
const editMode = ref(false)
const showEditInput = () => {
  editMode.value = !editMode.value;
};
</script>
<style scoped>
.main-container {
  width: 90%;
  height: 100%;
  background-color: #EFF2F9;
  border-radius: 20px;
}
.content-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-container {
  width: 100%;
  height: 5%;
  margin-top: 2%;
}
.title-text {
  width: 20%;
  font-size: 18px;
  height: 100%;
  margin-left: 20px;
  align-items: center;
  display: flex;
}
.subtitle-container {
  width: 100%;
  height: 5%;
  margin-top: 2%;
}
.subtitle-text {
  font-size: 16px;
  margin-left: 5%;
}
.info-container {
  width: 100%;
  height: 20%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.reference-container {
  width: 90%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.reference-item {
  margin: 0 1.5vh;
}
.chart-wrapper {
  width: 100%;
  height: 43%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chart-container {
  width: 90%;
  height: 100%;
  background-color: white;
  border-radius: 20px;
}
.chart {
  width: 95%;
  height: 100%;
}
.evaluation-wrapper {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}
</style>
